<!-- 批量入库 -->
<script lang="ts" setup>
import { ref, reactive, onMounted, watch } from 'vue'
import {
  NSpace,
  NButton,
  type FormInst,
  NForm,
  NFormItem,
  type FormRules,
  useMessage,
  NScrollbar,
  NSpin,
  NUpload,
  type UploadFileInfo,
  type DataTableColumns,
  NPagination,
  NDataTable,
  NModal,
  NProgress,
} from 'naive-ui'
import { sendRequest } from '@/utils/api'
import FixedAction from '@/components/FixedAction.vue'
import TableView from '@/components/TableView.vue'
import { useRoute } from 'vue-router'
import useRouteReplace from '@/hooks/useRouteReplace'
import VDialogContent from '@/views/OA/Common/DialogContent.vue'
const route = useRoute()
const routeReplace = useRouteReplace(route.query.redirect as string)
const tableData: any = ref()
const message = useMessage()
const userFormRef = ref<FormInst | null>(null)
const loading = ref(false)
const form: any = reactive({
  id: null,
  file: null
})
const dataTrue = ref([])
//筛选条件
const paginationReactive = reactive({
  page: 1,
  pageSize: 10,
  showSizePicker: true,
  pageSizes: [10, 20, 50, 100, 500],
  itemCount: 0,
  onChange: (page: number) => {
    paginationReactive.page = page
    tableData.value = dataTrue.value?.splice(
      paginationReactive.pageSize * (paginationReactive.page - 1),
      paginationReactive.pageSize * (paginationReactive.page - 1) + paginationReactive.pageSize
    )
  },
  onUpdatePageSize: (pageSize: number) => {
    paginationReactive.pageSize = pageSize
    paginationReactive.page = 1
    tableData.value = dataTrue.value?.splice(0, pageSize)
  }
})

const getLevel = (name: string) => (name ? ' > ' + name : '')
const columns: DataTableColumns = [
  {
    title: '序号',
    key: 'index',
    width: '5rem',
    align: 'center',
    render: (_, i) => {
      return ++i + (paginationReactive.page - 1) * paginationReactive.pageSize
    }
  },
  {
    title: '唯一编号',
    key: 'subItemCode',
    width: '10rem',
    align: 'center',
    ellipsis: {
      tooltip: true
    }
  },
  {
    title: '版本名称/完整书名',
    key: 'itemName',
    width: '5rem',
    align: 'center'
  },
  // {
  //   title: '资产码',
  //   key: 'assetCode',
  //   width: '5rem',
  //   align: 'center'
  // },
  // {
  //   title: '版本编号',
  //   key: 'subItemCode',
  //   width: '10rem',
  //   align: 'center'
  // },
  {
    title: '版本类型',
    key: 'itemTypeName',
    width: '10rem',
    align: 'center'
  },
  {
    title: '入库位置',
    key: 'collectTypeName',
    width: '10rem',
    align: 'center',
    render: (e: any) => {
      return (
        getLevel(e.firstLevelName) +
        getLevel(e.secondLevelName) +
        getLevel(e.threeLevelName) +
        getLevel(e.fourthLevelName) +
        getLevel(e.fifthLevelName) +
        getLevel(e.sixthLevelName)
      ).slice(3)
    }
  }
]
// 编目审核
const columns1: DataTableColumns = [
  {
    title: '序号',
    key: 'index',
    width: '5rem',
    align: 'center',
    render: (_, i) => {
      return ++i + (paginationReactive.page - 1) * paginationReactive.pageSize
    }
  },
  // {
  //   title: '唯一编号',
  //   key: 'subItemCode',
  //   width: '10rem',
  //   align: 'center',
  //   ellipsis: {
  //     tooltip: true
  //   }
  // },
  {
    title: '版本名称/完整书名',
    key: 'itemName',
    width: '5rem',
    align: 'center'
  },
  {
    title: '资产码',
    key: 'assetCode',
    width: '5rem',
    align: 'center'
  },
  // {
  //   title: '版本编号',
  //   key: 'subItemCode',
  //   width: '10rem',
  //   align: 'center'
  // },
  {
    title: '版本类型',
    key: 'itemTypeName',
    width: '10rem',
    align: 'center'
  },
  {
    title: '入库位置',
    key: 'collectTypeName',
    width: '10rem',
    align: 'center',
    render: (e: any) => {
      return (
        getLevel(e.firstLevelName) +
        getLevel(e.secondLevelName) +
        getLevel(e.threeLevelName) +
        getLevel(e.fourthLevelName) +
        getLevel(e.fifthLevelName) +
        getLevel(e.sixthLevelName)
      ).slice(3)
    }
  }
]

const formRules: FormRules = {
  file: {
    required: true,
    trigger: ['blur', 'change'],
    type: 'any',
    message: '不能为空'
  }
}
const percentage = ref(0)
const processVisible = ref(false)
const timer = ref<number | null>(null)
const tableLoading = ref()
const importErrorModalVisible = ref(false)
const importErrorMessage = ref('')
const importErrorExcelPath = ref('')
const isImportSuccess = ref(false)
const handleCancelImport = () => {
  importErrorModalVisible.value = false
}
const handleExport = () => {
  if (importErrorExcelPath.value) {
    const a = document.createElement('a')
    a.href = importErrorExcelPath.value
    a.download = '导入错误.xlsx'
    a.click()
  }
  importErrorModalVisible.value = false
}
const queryTableData = async (resetPage = false, file: any) => {
  if (resetPage) paginationReactive.page = 1
  tableLoading.value = true
  processVisible.value = true
  const [error, res] = await sendRequest({
    module: 'collectProcess',
    api: 'collectItemStorageImportFile',
    override: {
      data: {
        type: route?.query?.type, //1初编 2编目
        excel: file
      },
      onUploadProgress: (e: any) => {
        console.log(e.progress, e.loaded, e.total)
        const complete = Math.round((e.loaded * 100) / e.total)
        // percentage.value = Math.round((e.loaded * 100) / e.total)
        // 超过80 开始干涉
        if (complete >= 80) {
          if (timer.value) return
          timer.value = window.setInterval(() => {
            percentage.value += Math.round((100 - percentage.value) * 0.2) // 每次增加剩下的20%

            // 超过99 不再变化（此时也接近上传完成了）
            if (percentage.value > 99) {
              timer.value && window.clearInterval(timer.value)
            }
          }, 1000)
        } else {
          // 在80之前都按照axios计算出的进度来显示
          percentage.value = complete
        }
      }
    }
  })
  loading.value = false
  tableLoading.value = false
  if (error) return message.error(error.message)
  percentage.value = 100
  // 100加载完成再关闭进度条
  setTimeout(() => {
    console.log('结束')
  }, 500)
  timer.value && window.clearInterval(timer.value)
  processVisible.value = false
  if (res.code !== 0) return message.error(res.msg)
  isImportSuccess.value = res.data?.trueFlag
  importErrorMessage.value = res?.data.errorInfo
  importErrorExcelPath.value = res?.data.excelPath
  importErrorModalVisible.value = true
  dataTrue.value = res.data
  tableData.value = res.data?.splice(0, 10)
  paginationReactive.itemCount = res.data.length
}
const submit = async () => {
  if (!form.file) {
    message.info('请上传文件')
    return
  }
  // const validate = await Promise.all([
  //   new Promise((resolve, reject) => {
  //     userFormRef.value?.validate((error) => {
  //       if (error) return reject(error)
  //       resolve(true)
  //     })
  //   })
  // ])
  // if (!validate.every(Boolean)) return

  loading.value = true
  const [error, res] = await sendRequest({
    module: 'collectProcess',
    api: 'collectingItemsStagingbatchUpdate',
    override: {
      data: {
        itemsStagingList: tableData.value,
        type: route?.query?.type //1初编 2编目
      }
    }
  })
  loading.value = false

  if (error) return message.error(error.message)
  if (res.code !== 0) return message.error(res.msg)
  message.success(res.msg)
  routeReplace()
}
// 返回
const goBack = () => {
  // history.back()
  routeReplace()
}
//添加附件
const imgList = ref<any>([])

async function handleUploadChange(fileList: UploadFileInfo[]) {
  if (fileList.length == 0) {
    dataTrue.value = []
    tableData.value = []
    paginationReactive.itemCount = 0
    imgList.value = []
    return
  }
  imgList.value = [
    {
      id: fileList[0].file?.id,
      name: fileList[0].file?.name,
      status: 'finished',
      url: fileList[0].file?.fullPath
    }
  ]
  form.file = fileList[0].file
  queryTableData(false, fileList[0].file)
}
//下载
function download(headers: any, data: any, name?: string) {
  const val = headers['content-disposition']?.match(/(?<=filename=)(.*)/)
  let filename = val ? decodeURIComponent(val[0]) : name + '导出.xlsx'
  if (!filename.includes('xlsx')) {
    filename = filename.replace('xls', 'xlsx')
  }
  const a = document.createElement('a')
  let binaryData = []
  binaryData.push(data)
  a.href = window.URL.createObjectURL(new Blob(binaryData))
  a.download = filename
  a.click()
  window.URL.revokeObjectURL(a.href)
}
watch(
  () => route,
  () => {
    if (route.path == '/collection/process/InitCompilation/InAllStoreroom') {
      dataTrue.value = []
      tableData.value = []
      paginationReactive.itemCount = 0
      imgList.value = []
      form.file = null
    }
  },
  {
    deep: true,
    immediate: true
  }
)
const exportLoading = ref(false)
async function handleDownload() {
  exportLoading.value = true
  const [error, res, headers] = await sendRequest({
    module: 'collectProcess',
    api: route?.query?.type == '1' ? 'downloadTemplateStaging' : 'downloadFirstCatalogTemplate'
  })
  if (error) return message.error(error.message)
  download(headers, res)
  exportLoading.value = false
}
onMounted(async () => {})
</script>

<template>
  <div class="main">
    <div class="form_content">
      <NScrollbar>
        <NSpin :show="false">
          <div class="content">
            <div class="topTitle">藏品添加</div>
            <NForm
              :model="form"
              :rules="formRules"
              ref="userFormRef"
              label-placement="left"
              label-width="110"
              require-mark-placement="left"
            >
              <NSpace justify="start">
                <NFormItem
                  label="数据导入"
                  path="file"
                >
                  <NUpload
                    @update:file-list="handleUploadChange"
                    :file-list="imgList"
                    accept=".xlsx, .xls"
                    :max="1"
                  >
                    <NButton
                      type="warning"
                      style="width: 115px"
                      class="btnDownload"
                    >
                      上传文件
                    </NButton>
                    <!-- <NButton>上传文件</NButton> -->
                  </NUpload>
                </NFormItem>
                <NButton
                  type="warning"
                  style="width: 115px"
                  class="btnDownload"
                  @click="handleDownload"
                >
                  模板下载
                </NButton>
              </NSpace>
            </NForm>
            <div class="topTitle">入库藏品</div>
            <TableView class="table">
              <template #table="props">
                <NDataTable
                  v-bind="props"
                  :bordered="false"
                  :columns="route.query.type == '1' ? columns : columns1"
                  :data="tableData"
                  :loading="tableLoading"
                />
              </template>
              <template #pagination>
                <NPagination
                  show-size-picker
                  show-quick-jumper
                  :page-sizes="paginationReactive.pageSizes"
                  :item-count="paginationReactive.itemCount"
                  :page="paginationReactive.page"
                  :page-size="paginationReactive.pageSize"
                  @update:page="paginationReactive.onChange"
                  @update:page-size="paginationReactive.onUpdatePageSize"
                  :suffix="() => '页'"
                >
                  <template #prefix>
                    <span style="font-size: 14px">共{{ paginationReactive.itemCount }}条</span>
                  </template>
                </NPagination>
              </template>
            </TableView>
          </div>
        </NSpin>
      </NScrollbar>
    </div>
    <NModal
      :auto-focus="false"
      :mask-closable="false"
      v-model:show="processVisible"
    >
      <n-progress
        type="line"
        style="width: 200px"
        status="success"
        :percentage="percentage"
      >
        {{ percentage }}%
      </n-progress>
    </NModal>
    <NModal
    :auto-focus="false"
    v-model:show="importErrorModalVisible"
  >
    <VDialogContent
      @close="handleCancelImport"
      @submit="handleExport"
      title="导入提示"
      submit-text="导出错误报告"
      close-text="确定"
      :submitVisible="!isImportSuccess"
    >
      <p style="max-width: 400rem">
        {{ importErrorMessage }}
      </p>
    </VDialogContent>
  </NModal>
  </div>
  <FixedAction>
    <NSpace justify="center">
      <NButton
        style="width: 78px"
        ghost
        @click="goBack"
      >
        取消
      </NButton>
      <NButton
        type="primary"
        style="width: 78px"
        @click="submit"
        :loading="loading"
      >
        确定
      </NButton>
    </NSpace>
  </FixedAction>
</template>
<style scoped lang="scss">
@mixin CommonFont {
  font-size: 18rem;
  font-family: PingFangSC, PingFang SC;
  font-weight: 400;
  color: #333333;
}

.main {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100%;
  overflow: hidden;

  .form_content {
    width: 100%;
    height: 100%;
    padding: 20rem 20rem 0;

    .topTitle {
      font-size: 22px;
      font-family: PingFangSC, PingFang SC;
      font-weight: 500;
      color: #5fb17f;
      margin-bottom: 10rem;
    }

    .inputWH {
      width: 300rem;
    }

    .inputWHmin {
      width: 150rem;
    }

    .content {
      display: flex;
      flex-direction: column;
      width: 100%;
      height: 100%;
      padding: 18rem 33rem 120rem;
      overflow-y: scroll;
      background-color: #ebeceb;
      @include CommonFont;
    }
  }
}

.content::-webkit-scrollbar {
  display: none;
}

:deep(.n-spin-container) {
  width: 100%;
  height: 100%;
}

:deep(.n-scrollbar-container) {
  width: 100%;
  height: 100%;
}

:deep(.n-scrollbar-content) {
  width: 100%;
  height: 100%;
}

:deep(.n-spin-content) {
  width: 100%;
  height: 100%;
}
</style>
